<?php

namespace App\Http\Controllers\Api\Cocktail;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

use App\Model\Cocktail\Jiweijiu,App\Model\Cocktail\Search;

class ArticleController extends Controller
{
  //
  public function add(Request $request)
  {
    $name = trim($request->get('name',''));
    if ( Jiweijiu::checkRepeat($name) ) {
      return $this->apiResponse(1,'名称不能重复');
    }
    $obj = new Jiweijiu;
    $obj->name = $name;
    $obj->image = $request->get('image','');
    $obj->enable = $request->get('enable',0);
    $obj->classic = $request->get('classic',0);
    $obj->story = $request->get('story','');
    $obj->material = $request->get('material','');
    $obj->ware = $request->get('ware','');
    $obj->step = $request->get('step','');
    $obj->feature = $request->get('feature','');
    $obj->save();

    return $this->apiResponse();
  }


  public function edit(Request $request,$id)
  {
    $name = trim($request->get('name',''));
    if ( Jiweijiu::checkRepeat($name,$id) ) {
      return $this->apiResponse(1,'名称不能重复');
    }
    $obj = Jiweijiu::find($id);
    $obj->name = $name;
    $obj->image = $request->get('image','');
    $obj->enable = $request->get('enable',0);
    $obj->classic = $request->get('classic',0);
    $obj->story = $request->get('story','');
    $obj->material = $request->get('material','');
    $obj->ware = $request->get('ware','');
    $obj->step = $request->get('step','');
    $obj->feature = $request->get('feature','');
    $obj->save();

    return $this->apiResponse();
  }

  public function list()
  {
    $all = Jiweijiu::where('enable',1)->where('classic',1)->orderBy('id','desc')->take(5)->get(['id','name','image'])->toArray();
    foreach ($all as &$arr) {
      $arr['image'] = \Config::get('app.url').'/sys_images/'.$arr['image'];
    }
    return $this->apiResponse(0,'success',['all'=>$all]);
  }

  public function show($id)
  {
    $jiweijiu = Jiweijiu::find($id);
    $jiweijiu->count = $jiweijiu->count+1;
    $jiweijiu->save();
    $jiweijiu->image = \Config::get('app.url').'/sys_images/'.$jiweijiu->image;
    return $this->apiResponse(0,'success',['jiweijiu'=>$jiweijiu]);
  }

  // 
  public function search(Request $request)
  {
    $all = Jiweijiu::where('enable',1)->where('name','like','%'. $request->get('name','no') .'%')->orderBy('id','desc')->take(5)->get(['id','name','image'])->toArray();
    foreach ($all as &$arr) {
      $arr['image'] = \Config::get('app.url').'/sys_images/'.$arr['image'];
    }

    $name = $request->get('name','');
    if ( $name ) {
      $search = new Search;
      $search->name = $request->get('name','');
      $search->count = count($all);
      $search->save();
    }
    return $this->apiResponse(0,'success',['all'=>$all,'count'=>count($all)]);
  }

}
